#include "head.h"

MYSQL* mysql_connect(){
    MYSQL* mysql = mysql_init(NULL);
    if(mysql == NULL){
        printf("mysql init fail : %s\n",mysql_error(mysql));
        exit(1);
    }

    char mysql_user[100];
    bzero(mysql_user, sizeof(mysql_user));
    getparameter("mysql_user", mysql_user);

    char mysql_password[100];
    bzero(mysql_password, sizeof(mysql_password));
    getparameter("mysql_password", mysql_password);

    mysql = mysql_real_connect(mysql,"localhost",mysql_user,mysql_password,"WANG",0,NULL,0);
    /* mysql = mysql_real_connect(mysql,"localhost","root","123456","WANG",0,NULL,0); */
    if(mysql == NULL){
        printf("mysql connect fail : %s\n",mysql_error(mysql));
        exit(1);
    }
    printf("mysql connect\n");
    return mysql;
}
int isfile(MYSQL* mysql,char* file_path){
    printf("isfile\n");
    char* query = (char*)calloc(1024,sizeof(char));
    if(query == NULL){
        printf("query calloc fial\n");
    }
    else{
        printf("query calloc success\n");
    }
    snprintf(query,1024,"select file_id from file where path = \"%s\"",file_path);
    printf("%s\n",query);
    int err = mysql_query(mysql,query);
    if(err != 0){
        printf("err = %d\n",err);
        printf("isfile fail : %s\n",mysql_error(mysql));
        exit(1);
    }
    MYSQL_RES* result = mysql_store_result(mysql);
    printf("result == NULL : %s\n",mysql_error(mysql));
    printf("-------------\n");
    int rows = mysql_num_rows(result);
    int fields = mysql_num_fields(result);
    printf("rows=%d,fields=%d\n",rows,fields);
    MYSQL_ROW row = mysql_fetch_row(result);
    //printf("fileId=%s,atoi=%d\n",result,atoi(row[0]));
    int ans = rows == 0?-1:atoi(row[0]);
    mysql_free_result(result);
    return ans;
}
void insert_file(MYSQL* mysql,char* path,int user_id,int parent_dir_id,
                 int file_type,char* file_name,
                 char* hash1,char* hash2,int flag,int delet){

    char* query = (char*)calloc(1024,sizeof(char));
    snprintf(query,1024,"insert into file(path,user_id,Parent_dir_id,file_type,file_name,hash1,hash2,flag,`delete`)values(\"%s\",%d,%d,%d,\"%s\",\"%s\",\"%s\",%d,%d)"
             ,path,user_id,parent_dir_id,file_type,file_name,hash1,hash2,flag,delet);
    int err = mysql_query(mysql,query);
    if(err != 0){
        printf("isfile fail : %s\n",mysql_error(mysql));
        exit(1);
    }
}

int search_pfileid(MYSQL* mysql,char* path){
    char sql_buf[1024] = {0};
    sprintf(sql_buf,
            "select file_id from file where path =\"%s\"",
            path);

    if (mysql_query(mysql, sql_buf)) {
        printf("%s\n", mysql_error(mysql));
    }
    MYSQL_RES* result;
    MYSQL_ROW row;
    result= mysql_store_result(mysql);
    row = mysql_fetch_row(result);
    int pfile_id = atoi(row[0]);
    return pfile_id;
}

